// pages/myroom/myroom.js
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var WxParse = require('../../wxParse/wxParse.js');
var app = getApp();
var wxAuthFail = false;
var uid='';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    roomlist:[],
    isLoading:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    var inviteuid = options.inviteuid ? options.inviteuid : '';
    that.getLoginInfo();
    var roomstr = options.roomstr || '';
    if(roomstr!=''){

      var room = JSON.parse(roomstr);
    }
    var showIncome = options.showIncome || ''
    that.setData({
      showIncome: showIncome,
      room: room,
      roomstr: roomstr,
    })
   
    wx.setNavigationBarTitle({
      title: that.data.showIncome ? (room.building + ' ' + room.number) : "我的房间列表",
    })
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      // that.resetNavColor();
    });
    wx.getSystemInfo({
      success: function (res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
        });
      }
    });
    if (room) {
      that.getMyroomType("日租")
      that.getMyroomType("月租")
      that.getMyroomType("时租")
      that.getRoomInfo()

    }

    var test=new Date('2018/8/3').getTime() / 1000;
    console.log("test8.3",test);
    console.log("test8.3",new Date(test*1000));

    var test=new Date('2018/8/4').getTime() / 1000;
    console.log("test8.4",test);
    console.log("test8.4",new Date(test*1000));

    var test=new Date('2018/8/8').getTime() / 1000;
    console.log("test8.8",test);
    console.log("test8.8",new Date(test*1000));

    var test=new Date('2018/8/9').getTime() / 1000;
    console.log("test8.9",test);
    console.log("test8.9",new Date(test*1000));
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.uid ? that.data.uid : '';
    console.log("分享id" + inviteuid);
    if (util.orgid == '18535') {
      if (that.data.showIncome) {
        return {
          title: that.data.building + that.data.roomnumber + '，靓房献给你',
          path: '/pages/myroom/myroom?&inviteuid=' + inviteuid
        };

      }else{
        return {
          title: that.data.roomList[0].building + that.data.roomnumber + '，靓房献给你',
          path: '/pages/myroom/myroom?&inviteuid=' + inviteuid
        };
      }
    }
  },

  ////表单提交触发事件
  formSubmit: function (e) {
    app.saveFormId(e.detail.formId);
    

    var that = this;
    var res = e.detail.value;
    var username = res.username;
    var mobile = res.mobile;

    if (username == "") {
      var contentname = this.data.tc == 1 ? '姓名不能為空' : '姓名不能为空';
      wx.showModal({
        title: '提示',
        content: contentname,
        showCancel: false,
      })
      return;
    } else if (mobile == "") {
      var contentmobile = this.data.tc == 1 ? '手機號不能為空' : '手机号不能为空';
      wx.showModal({
        title: '提示',
        content: contentmobile,
        showCancel: false,
      })
      return;
    } 

    //提交代理商认证请求
    var ac = 'registeredupdate'
    var privatekey = utilMd5.hexMD5(that.data.uid + 'registeredupdate' + that.data.token);
    var params = {
      ac: ac,
      uid: that.data.uid,
      owner: username,
      phone: mobile,
      orgid: util.orgid,
      privatekey: privatekey
    };
    console.log('业主关联：', params);
    // return;

    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("提交业主关联信息：", responseData.data);
        if (!responseData.data.res) {
          wx.showModal({
            title: '提示',
            content: "关联信息不存在",
            showCancel: false,
          })
        } else {
          var contentsucess = this.data.tc == 1 ? '成功關聯業主' : '成功关联业主';
          that.loadMyroom();
          console.log("提交业主关联信息：", that.data.roomList);
          wx.showModal({
            title: '提示',
            content: contentsucess,
            showCancel: false,
            success: function (res) {
              // if (res.confirm) {
              //   wx.redirectTo({
              //     url: '/pages/join_pay/join_pay?coin=50&authtype=20',
              //   })
              // }
            }
          })
        }

      },
      fail: function (e) {
        var contentfail = this.data.tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },
  getLoginInfo: function () {
    var that = this;
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {

        //更新数据
        wxAuthFail = false;
        uid = res.uid;
        that.setData({
          uid: res.uid,
          token: res.token,
          loginUname: res.uname,
          openid: res.wxsmall_openid
        })
        that.loadMyroom();
      } else {
        wxAuthFail = true;
      }
    }, '')
  },
  //
  loadMyroom: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getMyroom",
        "uid": uid,
      },
      success: function (responseData) {
        console.log(responseData);
        that.setData({
          isLoading:false
        })
        wx.hideLoading()

        if (responseData.data.res != false) {
          that.setData({
            roomList: responseData.data
          });
          console.log("roomlist",that.data.roomList);

        }
      }
    });
  },
  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    if (this.data.roomstr){
      this.data.roomstr = JSON.stringify(this.data.room)
      url = url + "?roomstr=" + this.data.roomstr;
    }
    wx.navigateTo({
      url: url,
    })
  },
  showRoomIncome: function (e) {
    console.log("getRoomIncome", e);
    var room = e.currentTarget.dataset.room
    var roomid = e.currentTarget.dataset.room.id
    var roomnumber = e.currentTarget.dataset.room.number
    var building = e.currentTarget.dataset.room.building
    var that = this;
    that.setData({
      roomid: roomid
    })
    var roomstr=JSON.stringify(room);
    wx.navigateTo({
      url: '/pages/myroom/myroom?showIncome=1&roomstr=' + roomstr,
    })
  },
  switchChange: function (e) {
    console.log(e)
    var that = this;
    var status=e.detail.value==true?1:0;
    
    //提交代理商认证请求
    var ac = 'roomstatusupdate'
    var privatekey = utilMd5.hexMD5(that.data.uid + 'roomstatusupdate' + that.data.token);
    var params = {
      ac: ac,
      uid: that.data.uid,
      orgid: util.orgid,
      roomid: that.data.room.id,
      status: status,
      privatekey: privatekey
    };
    console.log('参数：', params);
    // return;

    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("信息：", responseData.data);
        if (!responseData.data.res) {
          wx.showModal({
            title: '提示',
            content: "更新失败",
            showCancel: false,
          })
        } else {
          var contentsucess = this.data.tc == 1 ? '成功更新' : '成功更新';
          
          that.getRoomInfo()
          wx.showModal({
            title: '提示',
            content: contentsucess,
            showCancel: false,
            success: function (res) {
              // if (res.confirm) {
              // }
            }
          })
        }

      },
      fail: function (e) {
        var contentfail = this.data.tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    });
  },
  getMyroomType: function (caizhi) {
    // console.log(e)
    var that = this;
    
    //提交代理商认证请求
    var ac = 'getMyroomType'
    var params = {
      "ac":ac,
      "orgid": util.orgid,
      "caizhi": caizhi,
      "postuid": that.data.room.buildingid,
      "publickey": util.publiccode,
    };
    console.log('参数：', params);
    // return;

    util.api({
      data: params,
      success: function (responseData) {
        console.log("信息：", responseData.data);
        
        if (!responseData.data.res) {
          var res = responseData.data
          for (var i = 0; i < res.length; i++) {
            res[i].topictitle = res[i].topictitle +'￥'+ res[i].sellprice/100
          }
          responseData.data=res
        }
        
        if (responseData.data.res!=false) {
          var temp = [{ id: null, topictitle: "不设",}]
          if (caizhi=="日租") {
            
            that.setData({
              goodsListDay: temp.concat(responseData.data)
            })           

          } else if (caizhi == "月租") {
            that.setData({
              goodsListMonth: temp.concat(responseData.data)
            })
          } else if (caizhi == "时租") {
            that.setData({
              goodsListHour: temp.concat(responseData.data)
            })
          }
        }

      }
    });
  },
  bindPickerChange:function(e){
    console.log(e);
    var that = this;
    var topicid = that.data.room.topicid;
     
    if (e.currentTarget.dataset.caizhi == "日租") {

      topicid = that.data.goodsListDay[e.detail.value].id 

    }
    if (e.currentTarget.dataset.caizhi == "月租") {

      topicid = that.data.goodsListMonth[e.detail.value].id 

    }
    if (e.currentTarget.dataset.caizhi == "时租") {
      
      topicid = that.data.goodsListHour[e.detail.value].id
      
    }
    //提交
    var ac = 'roomTopicidUpdate'
    var privatekey = utilMd5.hexMD5(that.data.uid + 'roomTopicidUpdate' + that.data.token);
    var params = {
      ac: ac,
      uid: that.data.uid,
      orgid: util.orgid,
      topicid: topicid,
      caizhi: e.currentTarget.dataset.caizhi,
      roomid: that.data.room.id,
      privatekey: privatekey,
      btime: that.getCurrentObj().getTime() / 1000
    };
    console.log('参数：', params);
    

    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("信息：", responseData.data);
        if (!responseData.data.res) {
          wx.showModal({
            title: '提示',
            content: "更新失败",
            showCancel: false,
          })
        } else {
          var contentsucess = this.data.tc == 1 ? '成功更新' : '成功更新';
          var room = responseData.data.res;
          room.status = room.status == '1' ? 1 : 0
          that.setData({
            room: room
          })
          that.getRoomInfo()
          wx.showModal({
            title: '提示',
            content: contentsucess,
            showCancel: false,
            success: function (res) {
              // if (res.confirm) {
              // }
            }
          })
        }

      },
      fail: function (e) {
        var contentfail = this.data.tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    });

  },

  getRoomInfo: function () {
    // console.log(e)
    var that = this;

    var ac = 'getRoomInfo'
    var params = {
      "ac": ac,
      "orgid": util.orgid,
      "roomid": that.data.room.id,
      "publickey": util.publiccode,
    };
    console.log('参数：', params);
    

    util.api({
      data: params,
      success: function (responseData) {
        console.log("返回信息：", responseData.data);
        if (responseData.data.res!=false) {

          that.setData({
            room: responseData.data.res
          })
          var room = that.data.room;
          room.status = room.status == '1' ? 1 : 0
          that.setData({
            room: room
          })
          console.log("that.data.room：", that.data.room);
        }
        console.log("that.data.room---：", that.data.room);

      }
    });
  },
  cleanService:function(){
    
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + 'postliuyan' + that.data.token);
    util.api({
      method: "POST",
      data: {
        ac: "postliuyan",
        uid: that.data.uid,
        uname: that.data.room.owner,
        phone: that.data.room.phone,
        message: "【申请服务】" + " 房间："+ that.data.room.number +  " 项目：打扫卫生",
        orgid: util.orgid,
        privatekey: privatekey
      },
      success: function (responseData) {
        console.log(responseData);
        if (responseData.data.res == true) {
          var contentname = this.data.tc == 1 ? '提交成功' : '提交成功';
          app.dialogToast(contentname, "success", function () {
            // wx.reLaunch({ url: '/pages/liuyan-center/liuyan-center' });
          })
        } else {
          wx.showToast({
            title: '提交失败',
            icon: 'success'
          })
        }

      }
    });
  },
  getCurrentObj: function () {
    var c_obj = new Date()
    var a = c_obj.getFullYear() + '/' + (c_obj.getMonth() + 1) + '/' + c_obj.getDate()
    return new Date(a)
  },
  getCurrentObj: function () {
    var c_obj = new Date()
    var a = c_obj.getFullYear() + '/' + (c_obj.getMonth() + 1) + '/' + c_obj.getDate()
    return new Date(a)
  },
})